from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from database import get_db
from models import User
from schemas import UserRegister, UserLogin, Token, UserResponse
from utils.auth_utils import (
    get_password_hash,
    verify_password,
    create_access_token
)
from logger import logging

router = APIRouter(prefix="/api/auth", tags=["认证"])


@router.post("/register", response_model=Token, status_code=status.HTTP_201_CREATED)
async def register(user_data: UserRegister, db: Session = Depends(get_db)):
    """
    用户注册接口

    - **username**: 用户名(3-50字符)
    - **password**: 密码(6-50字符)
    - **confirmPassword**: 确认密码
    - **email**: 邮箱
    """
    try:
        # 验证两次密码是否一致
        if user_data.password != user_data.confirmPassword:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="两次输入的密码不一致"
            )

        # 检查用户名是否已存在
        existing_user = db.query(User).filter(
            User.username == user_data.username).first()
        if existing_user:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="用户名已存在"
            )

        # 检查邮箱是否已存在
        existing_email = db.query(User).filter(
            User.email == user_data.email).first()
        if existing_email:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="邮箱已被注册"
            )

        # 创建新用户
        hashed_password = get_password_hash(user_data.password)
        new_user = User(
            username=user_data.username,
            email=user_data.email,
            hashed_password=hashed_password
        )

        db.add(new_user)
        db.commit()
        db.refresh(new_user)

        # 生成访问令牌
        access_token = create_access_token(data={"sub": new_user.username})

        logging.info(f"新用户注册成功: {new_user.username}")

        return Token(
            access_token=access_token,
            user=UserResponse.from_orm(new_user)
        )

    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"用户注册失败: {str(e)}")
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="注册失败,请稍后重试"
        )


@router.post("/login", response_model=Token)
async def login(login_data: UserLogin, db: Session = Depends(get_db)):
    """
    用户登录接口

    - **username**: 用户名
    - **password**: 密码
    """
    try:
        # 查找用户
        user = db.query(User).filter(
            User.username == login_data.username).first()

        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误"
            )

        # 验证密码
        if not verify_password(login_data.password, user.hashed_password):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误"
            )

        # 生成访问令牌
        access_token = create_access_token(data={"sub": user.username})

        logging.info(f"用户登录成功: {user.username}")

        return Token(
            access_token=access_token,
            user=UserResponse.from_orm(user)
        )

    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"用户登录失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="登录失败,请稍后重试"
        )
